'use client'
import React, { useEffect, useState } from 'react'
import { Space, Table, Tag, Radio, Button, Modal, Form, Input, Flex, message, Select ,Popconfirm} from 'antd';
import type { TableProps } from 'antd';
import moment from 'moment';
import axios from 'axios';
import Edits from '../edits';
import { useRouter } from 'next/navigation';
import {
  PlusOutlined,
  VerticalAlignBottomOutlined,
  VerticalAlignTopOutlined,
  OrderedListOutlined,
  CalendarOutlined,
  RightCircleOutlined,
  DeleteOutlined,
  ReloadOutlined,
  SearchOutlined
} from '@ant-design/icons';
interface DataType {
  id: string;
  dingdan: any,
  title: any,
  num: any,
  jine: any,
  money: any,
  date: number,
  Collect: number
}
// 多选框
const rowSelection: TableProps<DataType>['rowSelection'] = {
  onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  }
};


export default function page() {
  const router = useRouter()
  const [title, setTitle] = useState()
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [obj, setObj] = useState('添加')
  const [edit, setEdit] = useState({})
  const [form] = Form.useForm()
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
    form.resetFields();
  };
  // 渲染数据
  async function getTitle() {
    const res = await axios.get('http://localhost:3000/shoplist').then(res => res.data)
    setTitle(res)
  }
  useEffect(() => {
    getTitle()
  }, [])
  // 添加新数据
  const handleAdd = async (values: any) => {
    try {
      values.date = Date.now();
      // 默认回款状态未完成（0）
      values.Collect = 0;
      // 发送post请求到后端
      await axios.post('http://localhost:3000/shoplist', values);
      // 提示成功
      message.success('添加成功')
      // 关闭模态框
      setIsModalOpen(false);
      // 重新获取数据
      getTitle()
    } catch (err) {
      message.error('添加失败')
      console.log(err)
    }
  }
  const [selectionType] = useState<'checkbox' | 'radio'>('checkbox');
  const columns: TableProps<DataType>['columns'] = [
    {
      title: '关联订单',
      dataIndex: 'dingdan',
      sorter: (a, b) => a.dingdan - b.dingdan,
    },
    {
      title: '订单归属人',
      dataIndex: 'title',
      sorter: (a, b) => a.title - b.title,
    },
    {
      title: '汇款期次',
      dataIndex: 'num',
      sorter: (a, b) => a.num - b.num,
    },
    {
      title: '计划汇款金额',
      dataIndex: 'jine',
      sorter: (a, b) => a.jine - b.jine,
    },
    {
      title: '已汇款金额',
      dataIndex: 'money',
      sorter: (a, b) => a.money - b.money,
    },
    {
      title: '计划回款日期',
      dataIndex: 'date',
      sorter: (a, b) => a.date - b.date,
      render: (date) => {
        return <span>{moment(date).format('YYYY-MM-DD HH:mm:ss')}</span>
      }
    },
    {
      title: '回款状态',
      dataIndex: 'Collect',
      sorter: (a, b) => a.Collect - b.Collect,
      render: (Collect) => {
        let tag = ''
        if (Collect == 1) {
          tag = '已完成'
        } else if (Collect == 2) {
          tag = '已逾期'
        } else {
          tag = '未完成'
        }
        return <Tag>{tag}</Tag>
      }
    },
    {
      title: '操作',
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => {
            router.push(`/wzf/detail/${record.id}`)
          }}><RightCircleOutlined/>详情</Button>

          <Popconfirm
            title="系统提示"
            description="你确定要删除嘛?"
            onConfirm={async()=>{
              await axios.delete(`http://localhost:3000/shoplist/${record.id}`).then(res => {
                console.log(res)
                message.success('删除成功')
                getTitle()
              })
            }}
            okText="Yes"
            cancelText="No"
          >
            <Button danger><DeleteOutlined />删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ]
  const onReset = () => {
    form.resetFields();
    onFinish({})
  };
  const onFinish = async (values: any) => {
    console.log(values);
    await axios.get("http://localhost:3000/shoplist",
      {
        params: {
          dingdan: values.dingdan,
          Collect: values.Collect,
          date: values.date,
          title: values.title,
          num: values.num
        }
      }
    ).then(res => {
      setTitle(res.data)
    }

    )

  };

  return (
    <div>

      <div>
        <Flex>
          <Form
            form={form}
            onFinish={onFinish}
            layout="horizontal"
            style={{ maxWidth: 600 }}>
            <Space>
              <Form.Item name="dingdan" style={{ width: 120 }} >
                <Input placeholder="订单标题" />
              </Form.Item>
              <Form.Item name="Collect" style={{ width: 120 }}>
                <Select placeholder="回款状态"
                  options={[
                    { value: '1', label: '已完成' },
                    { value: '2', label: '已逾期' },
                    { value: '3', label: '未完成' },
                  ]}
                >
                </Select>
              </Form.Item>
              <Form.Item name="date" style={{ width: 120 }}>
                <Input placeholder="计划回款日期" />
              </Form.Item>
              <Form.Item name="title" style={{ width: 120 }}>
                <Select placeholder="订单所属人员">
                  <Select.Option value="赵小刚">赵小刚</Select.Option>
                  <Select.Option value="小王">小王</Select.Option>
                  <Select.Option value="蔡小红">蔡小红</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item name="num" style={{ width: 120 }}>
                <Select placeholder="汇款期次">
                  <Select.Option value="第1期(共4期)">第1期(共4期)</Select.Option>
                  <Select.Option value="第2期(共4期)">第2期(共4期)</Select.Option>
                  <Select.Option value="第3期(共4期)">第3期(共4期)</Select.Option>
                  <Select.Option value="第4期(共4期)">第4期(共4期)</Select.Option>
                </Select>
              </Form.Item>
              <Form.Item>
                <Button htmlType='submit'><SearchOutlined />查询</Button>
              </Form.Item>
              <Form.Item>
                <Button htmlType="button" onClick={onReset}><ReloadOutlined />重置</Button>
              </Form.Item>
            </Space>
          </Form>
        </Flex>
      </div>
      <div style={{display:'flex',justifyContent:'space-between',width:'100%',marginBottom:'20px'}}>
      <div>
      <Button type="primary" onClick={() => {
        showModal()
        setObj('添加')
        setEdit({})
      }}><PlusOutlined />
        添加
      </Button>
      <Button style={{margin:'0 20px'}}><VerticalAlignBottomOutlined />导入</Button>
      <Button><VerticalAlignTopOutlined />导出</Button>
      </div>
      <div style={{marginRight:'20px'}}>
        <Button style={{margin:'0 20px'}}><OrderedListOutlined />排序</Button>
        <Button><CalendarOutlined />列表</Button>
      </div>
      </div>
      <Modal footer={null} title={obj} open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        {
          isModalOpen ? <Edits obj={obj} handleOk={handleOk} handleAdd={handleAdd} key={new Date().getTime()} /> : null
        }

      </Modal>
      <Table<DataType> pagination={{ defaultPageSize:3 }} rowSelection={{ type: selectionType, ...rowSelection }} columns={columns} dataSource={title} rowKey="id" />
    </div>

  )
}



